// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const MAX_LIMIT = 100
//const templateId = 'GANLZOLIBPeVeTJ5walgnLEb-hGzp3zIdhFibBKfZIY'



// 发送模板信息
var sendMsg = async (item) =>{
  try {
    const result = await cloud.openapi.subscribeMessage.send({
      "touser": item._openid,
      "page": item.page,
      "data": {
        "thing2": {
          "value": item.contents[0].content.substr(0, 20)
        },
        "time3": {
          "value": item.noticeDate
        },
        "phrase4": {
          "value": item.remark
        }
      },
      "templateId": item.templateId,
    })
    // const remove = await db.collection('taskmsg').where({
    //   openid: item.openid
    // }).remove()

    const update = await db.collection('taskmsg').doc(item._id)
                  .update({
                    data: {
                      isSend: true,
                    },
                  });

    return result
  } catch (err) {
    console.log(err)
    return err
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  // 先取出集合记录总数
  const countResult = await db.collection('taskmsg').count()
  const total = countResult.total
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  const _ = db.command
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('taskmsg').skip(i * MAX_LIMIT).limit(MAX_LIMIT)
    .where({
      isSend: false,
      createDate: _.eq(new Date(new Date().toLocaleDateString()))
    })
    .get()
    tasks.push(promise)
  }
  // 等待所有
  var res = (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })

  for (let i = 0; i < res.data.length; i++) {
    sendMsg(res.data[i])
  }
}